package com.gzy.studentsociety.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String url = req.getRequestURI();

        // 定义不需要登录即可访问的URL
        boolean isPublicUrl = "/studentSociety/index.jsp".equals(url) ||
                "/studentSociety/".equals(url) ||
                "/studentSociety/student/login".equals(url) ||
                "/studentSociety/student/register".equals(url) ||
                "/studentSociety/register.jsp".equals(url);

        if (isPublicUrl) {
            chain.doFilter(req, res);
        } else {
            HttpSession session = req.getSession(false);
            String student = (String) session.getAttribute("student");

            if (student == null) {
                // 重定向到登录页面，并附带消息
                res.sendRedirect("/studentSociety?message=请登录");
            } else {
                chain.doFilter(req, res);
            }
        }
    }
}